﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication
{
    class IMDbRecordReader
    {
        private GzipStreamLineReader _lineReader;
        private string _currentPlot;
        public String CurrentPlot
        {
            get
            {
                return _currentPlot;
            }
        }

        private string _currentTitle;
        public String CurrentTitle
        {
            get
            {
                return _currentTitle;
            }
        }

        private FastMovieSearchString _currentFastTitleSearch;

        private Regex validTitle;
        public IMDbRecordReader(GzipStreamLineReader lineReader)
        {
            _lineReader = lineReader;
            validTitle = new Regex("^[a-zA-Z-\']+$");
        }

        public bool CompareTitleToCurrentRecord(FastMovieSearchString title)
        {
            return _currentFastTitleSearch.Equals(title);
        }

        public bool AdvanceToNextRecord()
        {
            while (true)
            {
                string s = _lineReader.GetNextLine();
                if (string.IsNullOrEmpty(s))
                    break;

                if (s.StartsWith("MV:"))
                {
                    _currentTitle = s.Substring(4);
                    _currentFastTitleSearch = new FastMovieSearchString(_currentTitle);

                    StringBuilder builder = new StringBuilder(1024);
                    string pl = string.Empty;
                    while (!string.IsNullOrEmpty((pl = _lineReader.GetNextLine())) && pl.StartsWith("PL:"))
                    {
                        builder.Append(pl.Substring(4));
                        builder.Append(" ");
                    }

                    _currentPlot = builder.ToString();
                    return true;
                }
                else
                    continue;
            }
            return false;
        }
    }
}
